import type { Request } from 'express';
import {
  responseSuccess,
  responseError,
  responseData,
} from '@/share/interface/standard';
import Base from '@/controller/public/MiniBaseController';
import { IModule } from '@/share/interface/module';
/* 
{
  "id": 1,
  "sender_id": 1000,
  "receiver_id": 2000,
  "content": "你好，我的肚子疼",
  "type": "text",
  "created_at": "2024-06-03T10:26:59.802Z"
} */
export class ConsultationController extends Base {
  async findAll() {
    const data = await this.consultationRepository.find({
      order: { created: 'ASC' },
    });
    const res = data.reduce((acc, item) => {
      if (acc[item.user_id]) {
        acc[item.user_id].chat.push(item);
      } else {
        acc[item.user_id] = { chat: [item] };
      }
      return acc;
    }, {});
    for (let [key, value] of Object.entries(res)) {
      const user = await this.userRepository.find({
        where: { id: +key },
        select: ['nick_name', 'phone', 'age', 'gender'],
        relations: [],
      });
      if (user) {
        Object.assign(value, user[0]);
      }
    }

    return responseSuccess(res);
  }

  async findAllByUser(req: Request) {
    const id = parseInt(req.params.id);
    const result = await this.consultationRepository.find({
      where: { user_id: id },
      order: { created: 'ASC' },
    });
    try {
      // await req.addModuleClick({
      //   module_name: IModule.Health,
      //   user_id: id,
      // });
      return responseSuccess(result);
    } catch (err) {
      return responseError(err);
    }
  }

  async createMessageForUser(req: Request) {
    const { content, type, user_id = req.user_id } = req.body;

    if (type !== 'question' && type !== 'answer') {
      return responseError(
        '消息类型只支持 question 和 answer，当前消息类型为 ' + type
      );
    }

    const user = await this.userRepository.findOne({
      where: { id: user_id },
    });
    if (!user) {
      return responseData({
        code: 201,
        msg: '用户不存在',
        data: null,
      });
    }

    await this.consultationRepository.save({
      content,
      type,
      user_id,
    });

    return responseSuccess();
  }

  // 清空信息
  async clearMessageForUser(req: Request) {
    const id = parseInt(req.params.id);
    const consultation = await this.consultationRepository.find({
      where: { user_id: id },
    });
    if (!consultation.length)
      return responseError('该用户无对话记录');
    await this.consultationRepository.delete({ user_id: id });
    return responseSuccess();
  }
}
